package com.wjs.spring.service.impl;

import com.wjs.spring.mapper.AccountMapper;
import com.wjs.spring.pojo.Account;
import com.wjs.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Transactional
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public Integer save(Account account) {
        return accountMapper.insert(account);
    }

    @Override
    public Integer deleteByActno(String actno) {
        return accountMapper.deleteByActno(actno);
    }

    @Override
    public Integer modify(Account account) {
        return accountMapper.update(account);
    }
    @Override
    public Account getByActno(String actno) {
        return accountMapper.selectByActno(actno);
    }

    @Override
    public List<Account> getAll() {
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromActno, String toActno, Integer money) {
        Account fromact = accountMapper.selectByActno(fromActno);
        if(fromact.getBalance()<money){
            throw new RuntimeException("账户余额不足");
        }
        Account toact = accountMapper.selectByActno(fromActno);
        fromact.setBalance(fromact.getBalance()-money);
        toact.setBalance(toact.getBalance()+money);
        Integer update = accountMapper.update(fromact);
        update += accountMapper.update(toact);
        if(update!=2){
            throw new RuntimeException("转账失败");
        }
    }
}
